<template>
  <div>
    <!-- 用户列表 -->

    <!-- 搜索框 -->

    <el-card>
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item>
          <el-input placeholder="搜索" v-model="pager.keyword"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="search"
            >搜索</el-button
          >
          <el-button
            type="primary"
            icon="el-icon-circle-plus-outline"
            @click="handleAdd"
            >添加</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>

    <!-- <div>
      <el-table :data="tableData" border style="width: 100%">
    表格内容水平居中   :cell-style="{ textAlign: 'center' }"
    </div> -->

    <el-table
      :data="tableData"
      border
      style="width: 100%"
      :header-cell-style="{ textAlign: 'center' }"
      :cell-style="{ textAlign: 'center' }"
    >
      <el-table-column fixed prop="id" label="Id" width="120">
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="120">
      </el-table-column>
      <el-table-column prop="nickname" label="昵称" width="120">
      </el-table-column>
      <el-table-column prop="roleName" label="角色名称" width="120">
        <!-- <el-button type="text" size="small">是</el-button>
        <el-button type="text" size="small">否</el-button> -->
      </el-table-column>
      <el-table-column prop="password" label="密码" width="100">
      </el-table-column>
      <el-table-column prop="isDeleted" label="是否删除" width="130">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.isDeleted ? 'danger' : 'primary '"
            size="small"
            >{{ scope.row.isDeleted ? "是" : "否" }}</el-tag
          >
        </template>

        <!-- <el-button type="text" size="small">是</el-button>
        <el-button type="text" size="small">否</el-button> -->
        <!-- <el-tag type="text" size="small">是</el-tag> -->
      </el-table-column>
      <el-table-column prop="isActived" label="是否启用" width="130">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isActived"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="changeSwitchs(scope.$index, scope.row)"
          >
          </el-switch>
        </template>
        <!-- <el-button type="text" size="small">是</el-button>
        <el-button type="text" size="small">否</el-button> -->
      </el-table-column>
      <el-table-column prop="createdTime" label="注册时间" width="350">
      </el-table-column>
      <el-table-column prop="remarks" label="备注" width="220">
      </el-table-column>
      <el-table-column fixed="right" prop="operation" label="操作" width="140">
        <template slot-scope="scope">
          <el-button
            @click="handleClick(scope.$index, scope.row)"
            type="text"
            size="small"
            icon="el-icon-edit"
            >编辑</el-button
          >
          <el-button
            type="text"
            size="small"
            icon="el-icon-delete"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 静态模态框，适用于增加和编辑 -->

    <el-dialog
      title="用户信息"
      :visible.sync="dialogFormVisible"
      style="overflow: hidden"
    >
      <el-form
        :model="formData"
        ref="elForm"
        :rules="rules"
        :label-position="labelPosition"
      >
        <el-form-item
          label="用户名"
          prop="username"
          :label-width="formLabelWidth"
        >
          <el-input clearable v-model="formData.username"></el-input>
        </el-form-item>
        <el-form-item
          label="昵称"
          prop="nickname"
          :label-width="formLabelWidth"
        >
          <el-input clearable v-model="formData.nickname"></el-input>
        </el-form-item>
        <el-form-item
          label="角色名称"
          prop="roleName"
          :label-width="formLabelWidth"
        >
          <el-select clearable v-model="formData.roleName" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.value"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
          :label-width="formLabelWidth"
        >
          <el-input clearable v-model="formData.password"></el-input>
        </el-form-item>

        <el-form-item label="备注" prop="remarks" :label-width="formLabelWidth">
          <el-input clearable v-model="formData.remarks"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分页组件 -->

    <div class="block">
      <el-pagination
        @size-change="handlePageSizeChange"
        @current-change="handlePageIndexChange"
        :current-page="pager.pageIndex"
        :page-size="pager.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pager.rowsTotal"
        background
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { getUsers, addUser, modUser } from '../../api/user'
import { getList } from '../../api/role'
import formatTime from '../../utils/formatTime'
import getColor from '../../utils/txorbg'

export default {
  mounted () {
    setTimeout(() => {
      console.log(this.tableData)
    }, 1500)
    this.fetchData(this.pager)
    // 获取角色名称列表
    getList({
      pageIndex: 1,
      pageSize: 100
    })
      .then((res) => {
        console.log(res.data.data.data)
        res.data.data.data.forEach((item) => {
          // id 和角色名称
          this.options.push({
            id: item.id,
            value: item.roleName
          })
        })
      })
      .catch((err) => {
        console.log(err)
      })
  },
  data () {
    return {
      formLabelWidth: '120px',
      currentIndex: 0,
      dialogFormVisible: false,
      labelPosition: 'left',
      pager: {
        pageIndex: 1,
        pageSize: 10,
        rowsTotal: 30,
        keyword: ''
      },
      //   复选框  角色属性
      options: [],
      value: '',
      tableData: [],
      formData: {
        id: 0,
        username: '',
        nickname: '',
        roleName: '',
        password: '',
        remarks: ''
      },
      rules: {
        username: [
          {
            required: true,
            message: '用户名不能为空',
            trigger: ['blur']
          },
          {
            pattern: /^[0-9a-zA-Z_]{1,}$/,
            message: '用户名格式不正确，必须是字母数字或下划线',
            trigger: ['blur']
          }
        ],
        password: [
          {
            required: true,
            message: '密码不能为空',
            trigger: ['blur']
          }
        ],
        roleName: [
          {
            required: true,
            message: '角色名称不能为空',
            trigger: ['blur']
          }
        ]
      }
    }
  },
  methods: {
    // 用户修改(编辑)
    handleClick (index, row) {
      console.log(row)
      this.dialogFormVisible = true
      this.formData.id = row.id
      this.formData.username = row.username
      this.formData.nickname = row.nickname
      this.formData.roleName = row.roleName
      this.formData.password = row.password
      this.formData.remarks = row.remarks
      this.formData.isActived = row.isActived

      // 编辑时获得当前表数组中的下标
      this.currentIndex = index
      console.log(index, row)
    },
    // 删除用户
    async handleDelete (index, row) {
      // 删除时获得当前数组的下标
      this.currentIndex = index
      row.isDeleted = true

      const res = await modUser(row.id, row)
      if (res.data.code === 200) {
        this.$message.success('删除成功')
      } else {
        row.isDeleted = false
        this.$message.error('删除失败')
      }
    },

    // 添加
    handleAdd () {
      this.dialogFormVisible = true
      this.formData.id = 0
      this.formData.username = ''
      this.formData.nickname = ''
      this.formData.roleName = ''
      this.formData.password = ''
      this.formData.remarks = ''
    },
    // 搜索
    search () {
      this.pager.pageIndex = 1
      this.pager.password = 10
      this.fetchData(this.pager)
      // this.$message.success('查找数据成功！')
    },
    // 模态框取消
    cancel () {
      this.dialogFormVisible = false
    },
    // 模态框确定(无论是添加还是修改后保存用户信息)
    handleSave () {
      this.$refs.elForm.validate((valid) => {
        if (!valid) return
        // TODO 提交表单

        console.log('没有错误', this.formData)
        // console.log(this.formData)
        // 如果表单中的id为0，则认为是添加用户，反之则为是修改用户
        if (this.formData.id === 0) {
          const us = this.formData
          us.txcolor = 'white'
          us.bgcolor = getColor()

          addUser(us)
            .then((data) => {
              console.log(data)
              // 将新添加的数据Push到现有表数据的里面
              if (data.data.code === 200) {
                const user = data.data.data.user
                user.roleName = data.data.data.roleName
                user.createdTime = formatTime(user.createdTime)
                this.tableData.push(user)
                this.pager.rowsTotal++
                this.dialogFormVisible = false
                this.$message.success(data.data.msg)
              } else {
                this.dialogFormVisible = false
                this.$message.warning(data.data.msg)
              }
            })
            .catch((err) => {
              console.log(err)
            })
        } else {
          modUser(this.formData.id, this.formData)
            .then((data) => {
              console.log(data)
              const obj = data.data.data
              obj.roleName = data.data.data.user.roleName
              obj.createdTime = formatTime(obj.createdTime)
              this.tableData.splice(this.currentIndex, 1, obj)
              this.dialogFormVisible = false
              this.$message.success(data.data.msg)
            })
            .catch((err) => {
              console.log(err)
            })
        }
      })
    },
    // switch开关
    async changeSwitchs (index, row) {
      console.log(index, row)
      const res = await modUser(row.id, row)
      console.log(res)
      if (res.data.code === 200) {
        this.$message.success('修改成功')
      } else {
        this.$message.error('修改失败')
      }
    },

    // 当页面大小发生改变的时候，重新拉取数据
    handlePageSizeChange (val) {
      console.log(val)
      this.pager.pageSize = val
      this.fetchData(this.pager)
    },
    // 当页面代码发生改变的时候，重新拉取数据
    handlePageIndexChange (val) {
      console.log(val)
      this.pager.pageIndex = val
      this.fetchData(this.pager)
    },

    // 拉取后台数据并且带上分页
    fetchData (pager) {
      getUsers(pager).then((data) => {
        data.data.data.data.forEach((item) => {
          item.createdTime = formatTime(item.createdTime)
        })

        console.log(data.data.data.data)
        this.tableData = data.data.data.data
        const pager = data.data.data.pager
        pager.keyword = this.pager.keyword
        this.pager = pager
      })
    }
  }
}
</script>
<style>
.block {
  text-align: center;
  /* display: flex; */
  margin-top: 15px;
}
</style>
